<template>
  <div class="hello">
    <el-button type="primary" v-on:click="add">添加元素</el-button>
    <br />
    <br />
    <svg id="drawing" class='mysvg' xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
      version="1.1">
    </svg>
  </div>
</template>

<script>
  import {
    SVG,
    Rect,
    extend as SVGextend,
    Element as SVGElement
  } from '@svgdotjs/svg.js'
  import '@svgdotjs/svg.draggable.js'
  import axios from 'axios'

  export default {
    name: 'Index',
    data() {
      return {
        msg: 'hello world',
        list: []
      }
    },
    methods: {
      add: function() {
        console.log('add a group')
        var draw = SVG('#drawing')
        var group = draw.group();
        var rect = draw.rect(100, 100).fill('#f03')
        rect.attr('id', this.getUUID());
        group.add(rect);
        rect.draggable();
        console.log('add rect id:' + rect.id())

        this.op(rect, 'INSERT');
        var that = this;
        rect.on('dragend.namespace', function(event) {
          console.log('move rect id:' + rect.id())
          that.$options.methods.syncPostion(this, event);
        });

      },
      getUUID: function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      },
      syncPostion: function(rect, event) {
        console.log(rect.id() + ',' + rect.x() + ',' + rect.y())
        this.op(rect, 'UPDATE');
      },

      op: function(rect, event) {
        console.log('rect:', rect)
        //后端请求
        var layerId = rect.id();
        var body = {
          'sketchId': 1
        };
        body['opType'] = event;
        var element = {};
        element['elementType'] = 'DRAW';
        element['elementContent'] = document.getElementById(rect.id()).innerHTML;
        element['layerId'] = layerId;
        element['extension'] = {
          'x': rect.x(),
          'y': rect.y()
        }
        var elements = [element];
        body['elements'] = elements;
        console.log('body:', body);
        //请求
        axios.post('/api/op', body)
          .then(function(response) {
            console.log('success:', response);
          })
          .catch(function(error) {
            console.log('error:', error);
          });
      },
      getSketchpad: function(id) {
        var that = this;
        axios.get('/api/sketchpad/get?sketchpadId=' + id)
          .then(function(response) {
            console.log(response.data);
            var draw = SVG('#drawing')
            var layers = response.data.content.layers;
            console.log(layers)

            layers.forEach(function(layer) {
              console.log(layer.layerId);
              var group = draw.group();
              var rect = draw.rect(100, 100).fill('#f03')
              rect.attr('id', layer.layerId);
              var extension = JSON.parse(layer.extension);
              rect.attr('x', extension.x);
              rect.attr('y', extension.y);
              group.add(rect);
              rect.draggable();

              rect.on('dragend.namespace', function(event) {
                console.log('move rect id:' + rect.id())
                that.$options.methods.syncPostion(this, event);
              });
            })
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      //只监听消息，不发送消息
      websocket: function() {
        var socket = null;
        console.log('connect start');
        socket = new WebSocket(
          "ws://localhost:8989/websocket?token=fKsRIs9nlFZJka-UPHsomhzYAb8mBbyzwn9-kqyuQZ4&appId=mirror-world&topic=push"
        );
        console.log('connect end');

        socket.onmessage = function(event) {
          var data = JSON.parse(event.data);
          console.log('socket.onmessage',data);
          if(data.appId=='mirror-world' && data.topic=='push'){
            var ele = JSON.parse(data.message)
            var elements = ele.elements;
            elements.forEach(function(e){
              var layerId = e.layerId;
              var extension = e.extension;

               var rect = new Rect(document.getElementById(layerId))
               rect.move(extension.x,extension.y)
               console.log(rect)
              // get rect from dom
              //var rect = SVG('#8ed9cce6-fb75-447c-bc29-5bce7389cb1c')
              //console.log(rect)
              //rect.move(extension.x,extension.y)
            })
          }
        };

        socket.onopen = function(event) {
          console.log('socket.onopen',event);
        };

        socket.onclose = function(event) {
          console.log('socket.onclose',event);
        };

      }
    },
    mounted() {
      this.getSketchpad(1);
      this.websocket();
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h1,
  h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }

  .mysvg {
    border: 1px solid #2C3E50;
    width: 1200px;
    height: 500px;
  }
</style>
